import {
	gbs
} from 'config/';
import { Subject } from 'rxjs/Rx';

const questionSubject = new Subject();
export default {
	name: 'editbook',
	components: {},
	data() {
		return {
			fields: [{
				key: 'answer',
				desc: '请输入回答',
				label: '回答'
			}, {
				key: 'is_correct',
				type: 'switch',
				label: '是否正确',
				value: {
					on: '是',
					off: '否'
				}
			}, {
				key: 'question_id',
				text: 'question_content',
				type: 'searchselect',
				subject: questionSubject,
				list: [],
				desc: '请选择问题',
				label: '搜索问题',
				remoteMethod: function (query) {
					window.vue_$.$$api_common_question({
						data: query,
						fn: data => {
							let list = [];
							if (data && data.length) {
								for (let question of data) {
									list.push({
										value: question.id,
										text: question.get('question')
									})
								}
								this.list = list;
							} else {
								this.list = [];
							}
						}
					});
				}
			}, {
				key: 'answer_index',
				desc: '请输入回答位置',
				label: '回答位置',
				type: 'inputnumber'
			}],
			default_value: {
				question_content: '',
				question_id: '',
				answer: '',
				answer_index: 1,
				is_correct: false
			},
			rules: {
				question: [{
					required: true, message: '请输入内容', trigger: 'blur'
				}],
				paragraph: [{
					required: true, message: '请输入段落', trigger: 'blur'
				}],
			}
		}
	},
	methods: {
		onSubmit({ data, info }) {
			console.log(data, info);
			//如果没有任何文本text，就检测html中是否包含图片img，iframe,如果都没有，代表真的没有数据。
			let param = data;
			if (this.$route.query.id) {
				this.$$api_answer_update({
					data: {
						id: param.id,
						data: param
					},
					fn: () => {
						this.$router.push('/main/answer/list');
					}
				});
			} else {
				this.$$api_answer_create({
					data,
					fn: () => {
						this.$router.push('/main/answer/list');
					}
				});
			}
		}
	},
	created() {
	},
	mounted() {
		setTimeout(() => {
			if (this.$route.query.id) {
				var data = this.$route.query.id;
				this.$$api_answer_find({
					data,
					fn: data => {
						questionSubject.next([{ value: data.question_id, text: data.question_content }]);
						this.default_value.id = data.id;
						this.default_value.question_content = data.question_content;
						this.default_value.question_id = data.question_id;
						this.default_value.answer = data.answer;
						this.default_value.answer_index = data.answer_index;
						this.default_value.is_correct = data.is_correct;
					}
				});
			}
			if (this.$route.query.question_id) {
				this.$$api_common_question({
					data: { id: this.$route.query.question_id },
					fn: data => {
						console.log('data::::', data);
						questionSubject.next([{ value: data[0].id, text: data[0].get('question') }]);
						this.default_value.question_id = data[0].id;
						this.default_value.question_content = data[0].get('question');
					}
				});
			}

		})
	},
	watch: {
		default_value: {
			deep: true,
			handler(v) {
				this.default_value = v;
			}
		}
	}
}